package com.xzt.ai.controller;

import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/sse/review")
public class SseControllerReview {

    @RequestMapping("/data")
    public void data(HttpServletResponse response) throws IOException, InterruptedException {
        log.info("data发送请求");
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();
        for (int i = 0; i < 10; i++) {
            String s = "data: " + new Date() + "\n\n";
            writer.write(s);
            writer.flush();
            Thread.sleep(1000);
        }
    }

    @RequestMapping("/retry")
    public void retry(HttpServletResponse response) throws IOException {
        log.info("retry发送请求");
        response.setContentType("text/event-stream;charset=utf-8");
        String s = "retry: 1000\n";
        s += "data: " + new Date() + "\n\n";
        PrintWriter writer = response.getWriter();
        writer.write(s);
        writer.flush();
    }

    @RequestMapping("/event")
    public void event(HttpServletResponse response) throws IOException {
        log.info("event发送请求");
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();
        for (int i = 0; i < 10; i++) {
            String s = "event: foo\n";
            s += "data: " + "加藤惠" + new Date() +"\n\n";
            writer.write(s);
            writer.flush();
        }
    }

    @RequestMapping("/end")
    public void end(HttpServletResponse response) throws IOException, InterruptedException {
        log.info("end发送请求");
        response.setContentType("text/event-stream;charset=utf-8");
        PrintWriter writer = response.getWriter();
        for (int i = 0; i < 10; i++) {
            String s = "event: foo\n";
            s += "data: " + "加藤惠" + new Date() +"\n\n";
            writer.write(s);
            writer.flush();
            Thread.sleep(1000);
        }
        String end = "event: end\n";
        writer.write(end+"data: EOF\n\n");
        writer.flush();
    }



}
